/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tradeplus.security;

import com.tradeplus.security.service.UserDetailsService;
import com.tradeplus.jms.EmailService;
import com.tradeplus.security.model.User;
import com.tradeplus.util.TPLController;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author ronnie
 */
public class SecurityController extends TPLController {
    
    private final String LOGOUT_URL = "/panelist/j_spring_security_logout";
    private final String LOGIN_FAILURE_URL = "/compass/security/LoginFailure.cps";
    
    private final String PANELIST_PAGE = "/panelist/PanelistHome.btp";
    private final String CUSTOMER_PAGE = "/customer/CustomerHome.btp";
    
    private final String CUSTOMIZE_ERROR = "/speaglobe/help/CustomError.btp";
    
    private final String ADMIN_PAGE="/admin/AdminHome.btp";
    
    private UserDetailsService userDetailsService;
    
    private EmailService emailService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
    
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }
    
    public ModelAndView Login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String errorLogin = request.getParameter("error_login");

        HashMap model = new HashMap();
        model.put("errorLogin", errorLogin == null ? "" : errorLogin);

        return new ModelAndView("/security/login", model);
    }
    
    public ModelAndView PasswordRequest(HttpServletRequest request, HttpServletResponse response)
    				throws Exception {
    	
    	HashMap map = new HashMap();
    	map.put("success", "");

    	return new ModelAndView("/security/password_request", map);
    }
    
    public ModelAndView PasswordRequestValidateEmail(HttpServletRequest request, HttpServletResponse response)
					throws Exception {
            HashMap map = new HashMap();
            String msg = "Email successfully sent. Please <a href=\"Login.dbv\">click here</a> to logon.";
            String success = "false";

            String emailAddress = request.getParameter("email");

            User user = userDetailsService.getUserByEmail(emailAddress);

            if(user == null) {
                    msg = "Email address "+emailAddress+" does not exist.";    			
            } else {		
                    if(emailService.sendPasswordRequestEmail(emailAddress, user, getServletContext())) {
                            success = "true";
                    } else {
                            msg = "Email sending failed!";
                    }

            }    	

            map.put("success", success);
            map.put("message", msg);

            return new ModelAndView("/security/password_request", map);
    }
    
    public void Logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
	response.sendRedirect(LOGOUT_URL);
    }
    
    public void LoginFailure(HttpServletRequest request, HttpServletResponse response)
	    throws Exception {
    	response.sendRedirect(LOGIN_FAILURE_URL);
    }
    
    public void Welcome(HttpServletRequest request, HttpServletResponse response) {

	BTPAuthenticationToken token = (BTPAuthenticationToken) request.getUserPrincipal();

        try {

            try {
                User user = userDetailsService.getUser(token.getUserID());

                if(user != null) {
                    if(user.hasRole("ROLE_PANELIST")) {
                        response.sendRedirect(this.PANELIST_PAGE);
                    } else if(user.hasRole("ROLE_ADMIN")) {
                        response.sendRedirect(this.ADMIN_PAGE);
                    } else {
                        response.sendRedirect(this.CUSTOMER_PAGE);
                    }
                } else {
                    response.sendRedirect(this.CUSTOMIZE_ERROR);
                }

            } catch(IOException ioe) {
                logger.error("Welcome(HttpServletRequest, HttpServletResponse)", ioe);
                response.sendRedirect(this.CUSTOMIZE_ERROR);
            }
        } catch(Exception e) {
            logger.error("Welcome(HttpServletRequest, HttpServletResponse)", e);
            e.printStackTrace();
        }
    }
}
